import json
import random
import time
import requests

from db import *
from spider_xue.settings import HEADERS
from spider_xue.ip import headers_list

mg = {
    "msgtype": "markdown",
    "markdown": {
        "title": "发言",
        "text": "#### NGAxx发言 \n> 9度，西北风1级，空气良89，相对温度73%\n #### 禾佬发言 \n> 10点20分发布 [天气](https://www.dingtalk.com) \n"
    }
}

dingurl = "https://oapi.dingtalk.com/robot/send?access_token=6d9c15f33519793287e97bef22403dc1875620fc3bcce9a73309ca3f84f11552"
ll = [
    {"url": "https://xueqiu.com/v4/statuses/user_timeline.json?page=1&user_id=1724351091",
     'dingurl': dingurl,
     "name": "云子在"},
    {"url": "https://xueqiu.com/v4/statuses/user_timeline.json?page=1&user_id=6781224586",
        'dingurl': dingurl,
        "name": 'maomao'},
    {'url': "https://xueqiu.com/v4/statuses/user_timeline.json?page=1&user_id=6357959113&_=1640158348522",
     'dingurl': dingurl,
     "name": '意如流水任西东'}
]


def get_request(url):
    hd = HEADERS
    hd['user-agent'] = random.choice(headers_list)
    hd['cookie'] = account_db.find_one({"phone": "chrome_x0"})['cookies']
    res = requests.get(url, headers=hd)
    return res.json()


def mian_do():
    for z in ll:
        try:
            res = get_request(z['url'])
            msg_list = []
            for i in res['statuses']:
                x = {}
                x['id'] = i['id']
                x['text'] = i['text']
                x['name'] = z['name']
                x['ts'] = time.strftime(
                    '%Y-%m-%d %H:%M:%S', time.localtime(int(i['created_at'] / 1000)))
                dd = snowball_msg_db.find_one({"id": i['id']})
                if dd:
                    if dd['text'] != i['text']:
                        snowball_msg_db.update_one({'id': x['id']}, {"$set": x}, upsert=True)
                        msg_list.append(x)
                        copy_x = x
                        copy_x['id'] = copy_x['id'] / 10
                        copy_x['text'] = dd['txex']
                        snowball_msg_db.update_one({'id': copy_x['id']}, {"$set": copy_x}, upsert=True)
                else:
                    snowball_msg_db.update_one({'id': x['id']}, {"$set": x}, upsert=True)
                    msg_list.append(x)
            send_msg(msg_list, mg, z['dingurl'], z['name'])
        except Exception as e:
            print(str(e))
            send_error(z['dingurl'], str(e), z['name'])


def send_msg(msg_list, mg, ding_url, name):
    headers = {
        'Content-Type': 'application/json'
    }
    for i in msg_list:
        mg["markdown"]["text"] = name + "--" + str(i["id"]) + '\n' + str(i["text"]).replace("<", ',').replace(
            "/>", ',').replace("/p>", ',').replace("p>", ',').replace("br", ',') + '\n' + i['ts']
        print(mg["markdown"]["text"])
        x = requests.post(ding_url, data=json.dumps(mg), headers=headers)
        print(x.text)
        if x.json() and x.json().get('errmsg') != 'ok':
            send_error(ding_url, str(x.json()), name)
        time.sleep(1)


def send_error(ding_url, eee, name):
    mg['markdown']['text'] = eee
    mg['at']['isAtAll'] = True
    headers = {
        'Content-Type': 'application/json'
    }
    mg["markdown"]["text"] = name + eee
    requests.post(ding_url, data=json.dumps(mg), headers=headers)
    time.sleep(1)
